shuffleDeck
Arrays Sandbox PanosP Revised

Shuffling a Deck of Cards

Problem
=======

Assuming we have an array containing a deck of cards, we want
to shuffle the deck, that is rearange the array items in a random order.

Solution
========

We'll develop a simple function and pass the _deck_ (the array of "cards")
as the first parameter to that function.
The cards' array (_deck_) is a number indexed, 0 based (0, 1, 2,...)
array, while the cards' _count_ (how many cards are in the deck)
will be passed to the function as a second parameter
for more flexibility.
So, having a classic deck of 52 cards in array `deck`, we'll call
the function as:

  shuffleDeck(deck, 52)

After calling the function, the `deck` array must have been shuffled
and ready to deal. Here is the code:

 function shuffleDeck(deck, count,		i, n, card) {
 	seed(1) 
 	for (i = 0; i < count; i++) {
 		n = int(rand() * count)
 		card = deck[i]
 		deck[i] = deck[n]
 		deck[n] = card
 	}
 }

That's all, folks!

Shuffling a Deck of Cards in Action
-----------------------------------

Here is a complete program demonstrating the `shuffleDec` function:

 function ShuffleDeck52(		deck) {
 	newDeck52(deck)
 	shuffleDeck(deck, 52)
 	dealDeck(deck, 52)
 }

Create a new deck. 52 cards will be placed in that new
deck, not shuffled by any means. Instead, the cards will
be ordered by suit and order (Ace, 2, 3,... 10, J, Q, K).
The order of suits is undefined.

 function newDeck52(deck,	suits, figure, suit, i, n) {
	delete deck
 	suits["spades"]
 	suits["clubs"]
 	suits["diamonds"]
 	suits["hearts"]
	for (i = 2; i <= 10; i++)
 		figure[i] = i
 	figure[1] = "A"
 	figure[11] = "J"
 	figure[12] = "Q"
 	figure[13] = "K"
 	for (suit in suits) {
 		for (i = 1; i <= 13; i++)
 			deck[n++] = figure[i] " of " suit
 	}
 }
  
 function dealDeck(deck, count,		i) {
 	for (i = 0; i < count; i++)
 		print deck[i]
 }

Author
======

Panos Papadopoulos

